package org.zoomdev.zoom.web.parameter;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.modules.CoreWebModule;
import org.zoomdev.zoom.web.parameter.pre.impl.FormPreParamParser;
import org.zoomdev.zoom.web.parameter.pre.impl.JsonPreParamParser;
import org.zoomdev.zoom.web.parameter.pre.impl.UploadPreParamParser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class PreParameterParserManager implements PreParameterParser {

    private static final Logger log = LoggerFactory.getLogger(CoreWebModule.class);
    private PreParameterParser[] parsers;


    public PreParameterParserManager(String uploadPath) {
        try {
            parsers = new PreParameterParser[]{
                    new JsonPreParamParser(),
                    new UploadPreParamParser(uploadPath),
                    new FormPreParamParser()
            };
        } catch (Throwable t) {
            log.warn("====不支持文件上传类型解析,若要支持，请添加相关依赖commons-fileupload=====");
            parsers = new PreParameterParser[]{
                    new JsonPreParamParser(),
                    new FormPreParamParser()
            };
        }

    }


    @Override
    public PreParameter preParse(ActionContext context) throws Exception {
        HttpServletRequest request = context.getRequest();
        assert (request != null);
        for (PreParameterParser preParameterParser : parsers) {
            PreParameter data = preParameterParser.preParse(context);
            if (data != null) {
                return data;
            }
        }

        throw new ZoomException("找不到参数预解析器" + request.getServletPath() + ":" + request.getContentType());
    }


    public void add(PreParameterParser parser) {
        List<PreParameterParser> list = new ArrayList<PreParameterParser>();
        list.add(parser);
        Collections.addAll(list, parsers);
        this.parsers = list.toArray(new PreParameterParser[list.size()]);
    }
}
